package geektime.io.nio2;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

/**
 * 异步io实现的服务端
 */
public class AsyncSocketClient {
    public static void main(String[] args) {
        // 创建一个客户端的异步通道
        try(AsynchronousSocketChannel client = AsynchronousSocketChannel.open();) {
            // 绑定ip和端口，并阻塞等待连接
            Future<Void> connectFuture = client.connect(new InetSocketAddress("localhost", 1234));
            connectFuture.get();
            // 和服务端连接成功后，向服务端发送信息
            String msg = "How are you?";
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            buffer.put(msg.getBytes());
            buffer.flip();
            Future<Integer> writeFuture = client.write(buffer);
            System.out.println("Sending msg to server...");
            writeFuture.get();
            System.out.println("Sent msg to server: " + msg);
            // 接收服务端发送回来的信息
            buffer.clear();
            Future<Integer> readFuture = client.read(buffer);
            System.out.println("Receiving msg from server...");
            readFuture.get();
            System.out.println("Received msg from server: " + getCurrentMessage(buffer));
            buffer.clear();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }

    public static String getCurrentMessage(ByteBuffer buffer) {
        byte[] bytes = new byte[buffer.position()];
        int i = 0;
        buffer.flip();
        while (buffer.hasRemaining()) {
            bytes[i++] = buffer.get();
        }
        return new String(bytes);
    }
}
